/* eslint-disable array-callback-return */
import React from 'react';
import { CloseOutlined, DownloadOutlined, PlusOutlined, UploadOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Table, Select, message, Modal, Row, Col, Divider, Upload } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import downloadFile, { matchDict, requestHeadersMd5 } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ loading }) => ({
  loading: loading.effects['custedit/invoiceSubmit'] ? false : loading.models.custedit,
  submitLoading: loading.effects['custedit/invoiceSubmit'],
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      nowPage: 1,
      pageNum: 10,
      cmTotal: 10,
      custId: null,
      taxerIdNoS: null,
      vatCoprNameS: null,
      invTypeList: [],
      selectedRowKeys: [],
      isAdd: true,
      modalVisible: false,
      uploadUrl: '/csApi/fileServer/uploadFile',
      downloadUrl: '/csApi/fileServer/downloadFile',
      newFlieList: [],
      oldFileList: [],
      fileList: [],
      isRequired: false,
    };
    this.columns = [
      {
        title: '增值税单位名称',
        dataIndex: 'vatCoprName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '发票类型',
        dataIndex: 'invTypeName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '纳税人识别号',
        dataIndex: 'taxerIdNo',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开户行',
        dataIndex: 'bankOfDepoName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '银行账号',
        dataIndex: 'bankAcco',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开票电话',
        dataIndex: 'invPhone',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '开票地址',
        dataIndex: 'invAddr',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '备注',
        dataIndex: 'remark',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <span className="editable-row-operations">
            <a onClick={e => this.update(e, record.invId)}>修改</a>
            <Divider type="vertical" />
            <a onClick={e => this.delList(e, record)}>删除</a>
          </span>
        ),
      },
    ];
  }

  componentDidMount = () => {
    const { custId, invTypeList } = this.props;
    const { nowPage, pageNum } = this.state;
    this.setState({ custId, invTypeList });
    this.getList(nowPage, pageNum);
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { custId, dispatch } = this.props;
    const { taxerIdNoS, vatCoprNameS, invTypeList } = this.state;
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
      orderBy: ' INV_ID DESC',
    };
    const params = { custId, taxerIdNo: taxerIdNoS, vatCoprName: vatCoprNameS, pageArg };
    dispatch({
      type: 'custedit/getInvoiceList',
      payload: params,
    }).then(res => {
      if (res.success) {
        const data = res.data.pageRecords;
        data.map(item => {
          const temp = item;
          temp.invType = matchDict(invTypeList, item.invType);
          temp.remark = item.remark ? item.remark : '--';
        });
        this.setState({
          dataSource: res.data.pageRecords,
          cmTotal: res.data.totalCount,
        });
      } else {
        this.setState({ cmTotal: 0, dataSource: [] });
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  };

  // 删除数据
  delList = (e, record) => {
    e.preventDefault();
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const rowKeys = [];
    const rows = [];
    rowKeys.push(record.invId);
    rows.push(record);
    this.setState({ selectedRowKeys: rowKeys });
    confirm({
      icon: <QuestionCircleOutlined />,
      title: '你确定要刪除此条发票信息吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'custedit/invoiceDel',
          payload: { generalIds: rowKeys },
        }).then(res => {
          if (res.success) {
            const { cmTotal, nowPage, pageNum } = this.state;
            const selectedLen = selectedRowKeys.length;
            if (nowPage > 1 && (cmTotal % pageNum === selectedLen || pageNum === selectedLen)) {
              this.getList(nowPage - 1, pageNum);
              this.setState({ nowPage: nowPage - 1 });
            } else {
              this.getList(nowPage, pageNum);
            }
            this.setState({ selectedRowKeys: [] });
            message.success('删除成功！');
          } else {
            message.warning(`${res.message || '删除失败！'}`);
          }
        });
      },
      onCancel: () => {
        this.setState({ fileList: [] });
      },
    });
  };

  // 新增数据
  add = () => {
    const { form } = this.props;
    this.handleModalVisible(true, true);
    form.resetFields();
  };

  // 修改数据
  update = (e, invId) => {
    e.preventDefault();
    const { dispatch, form, custId } = this.props;
    const rowKeys = [];
    rowKeys.push(invId);
    this.setState({ selectedRowKeys: rowKeys });
    if (custId) {
      dispatch({
        type: 'custedit/getInvoiceInfo',
        payload: { invId },
      }).then(res => {
        if (res.success && res.data) {
          this.handleModalVisible(true, false);
          const getFieldsList = form.getFieldsValue();
          Object.keys(res.data).forEach(key => {
            if (res.data[key]) {
              if (key === 'invType') {
                res.data[key] = `${res.data[key]}`;
                if (res.data[key] === '1') {
                  this.setState({ isRequired: true });
                } else {
                  this.setState({ isRequired: false });
                }
              }
            }
          });
          Object.keys(getFieldsList).forEach(key => {
            if (res.data[key]) {
              if (key === 'invType') {
                form.setFieldsValue({ [key]: { key: res.data[key] } });
              } else {
                form.setFieldsValue({ [key]: res.data[key] });
              }
            }
          });
          if (res.data.invoiceAffixList && res.data.invoiceAffixList.length) {
            this.setState({ oldFileList: res.data.invoiceAffixList });
          }
        } else {
          message.warning(`${res.message || '暂无数据！'}`);
        }
      });
    }
  };

  // 切换模态框：新增、修改
  handleModalVisible = (flag, isAdd) => {
    this.setState({
      modalVisible: !!flag,
      isAdd,
      newFlieList: [],
    });
  };

  // 取消关闭模态框
  cancelModal = () => {
    this.handleModalVisible(false, true);
    this.setState({ selectedRowKeys: [], fileList: [] });
  };

  // 选择发票类型
  selectinvType = value => {
    if (value.key === '1') {
      this.setState({ isRequired: true });
    } else {
      this.setState({ isRequired: false });
    }
  };

  // 文件上传
  changeUpload = (info, listContFile) => {
    const { file, fileList } = info;
    const { downloadUrl } = this.state;
    const newData = listContFile.map(item => ({ ...item }));
    if (file.status === 'done' && file.response.success) {
      const fileId = file.response.data.split('|')[0];
      const fileName = file.response.data.split('|')[1];
      fileList.map(files => {
        const temp = files;
        temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
        temp.linkProps = { download: `${fileName}` };
      });
      newData.push({
        uid: file.uid,
        custAffixId: fileId,
        affixName: fileName,
      });
      this.setState({ newFlieList: newData });
      message.success('文件上传成功！');
    }
    if ((file.status === 'done' && !file.response.success) || file.status === 'error') {
      message.error('上传失败！');
    }
    this.setState({ fileList });
    return fileList;
  };

  // 移除文件
  removeFile = (file, listContFile) => {
    const newData = listContFile.filter(item => item.uid !== file.uid);
    this.setState({ newFlieList: newData });
  };

  // 删除页面素材文件
  delFile = (id, oldFileList) => {
    const newData = oldFileList.filter(item => item.custAffixId !== id);
    this.setState({ oldFileList: newData });
  };

  // 新增修改提交数据
  submitData = () => {
    const {
      isAdd,
      custId,
      selectedRowKeys,
      nowPage,
      pageNum,
      oldFileList,
      newFlieList,
    } = this.state;
    const { form, dispatch } = this.props;
    let submitData = {};
    let invoiceAffixList = {};
    const submitUrl = isAdd ? '/csApi/invoice/insert' : '/csApi/invoice/update';
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const temp = values;
        delete temp.vatCoprNameS;
        delete temp.taxerIdNoS;
        delete temp.invoiceLicense;
        Object.keys(values).forEach(key => {
          const obj = values;
          if (values[key] && values[key].key) {
            obj[key] = values[key].key;
          } else {
            obj[key] = values[key] ? values[key] : '';
          }
        });
        delete temp.invoiceAffixList;
        if (oldFileList.length) {
          oldFileList.map(f => {
            const ff = f;
            delete ff.custId;
            delete ff.affixType;
            delete ff.glInfoId;
          });
        }
        if (newFlieList.length) {
          newFlieList.map(f => {
            const object = f;
            delete object.uid;
          });
        }
        invoiceAffixList = isAdd ? newFlieList : newFlieList.concat(oldFileList);
        submitData = isAdd
          ? { custId, ...values, invoiceAffixList }
          : { custId, ...values, invId: selectedRowKeys[0], invoiceAffixList };
        dispatch({
          type: 'custedit/invoiceSubmit',
          payload: { submitUrl, submitData },
        }).then(res => {
          if (res.success) {
            message.success(`${res.message || (isAdd ? '新增成功！' : '修改成功！')}`);
            this.setState({ selectedRowKeys: [], fileList: [], modalVisible: false });
            this.getList(nowPage, pageNum);
          } else {
            message.warning(`${res.message || (isAdd ? '新增失败！' : '修改失败！')}`);
          }
        });
      }
    });
  };

  // 导出数据
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      confirm({
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { custId, selectedRowKeys } = this.state;
    const params = { custId, invIds: selectedRowKeys };
    downloadFile(params, '/csApi/invoice/expInvoice', 'POST');
  };

  render() {
    const {
      dataSource,
      selectedRowKeys,
      modalVisible,
      isAdd,
      invTypeList,
      uploadUrl,
      newFlieList,
      oldFileList,
      custId,
      isRequired,
      nowPage,
      pageNum,
      cmTotal,
      fileList,
    } = this.state;
    const {
      form: { getFieldDecorator },
      loading,
      submitLoading,
    } = this.props;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,

      onChange: rows => {
        this.setState({ selectedRowKeys: rows });
      },
    };
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: nowPage, // 默认当前页
      defaultPageSize: pageNum, // 默认单页条数
      current: nowPage, // 当前页
      pageSize: pageNum, // 单页条数
      total: cmTotal, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.setState({ nowPage: page, pageNum: pageSize });
        this.getList(page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.setState({ nowPage: current, pageNum: size });
        this.getList(current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${nowPage} / ${totalPage}页`;
      },
    };
    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      title: isAdd ? '新增发票信息' : '修改发票信息',
      visible: modalVisible,
      confirmLoading: submitLoading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: this.cancelModal,
      destroyOnClose: true,
    };
    // 下拉选项
    // 发票类型
    const invTypeOL = invTypeList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    // 文件上传
    const uploadProps = {
      action: uploadUrl,
      headers: requestHeadersMd5(),
      fileList,
      onChange: info => this.changeUpload(info, newFlieList),
      onRemove: file => this.removeFile(file, newFlieList),
    };
    return (
      <div>
        <Row style={{ marginBottom: '20px' }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.add}>
            <PlusOutlined />
            新增
          </Button>
          <Button
            style={{ marginRight: 20 }}
            icon={<UploadOutlined />}
            onClick={() => router.push(`/salemanage/customer/uploadinfo?custId=${custId}`)}
          >
            批量上传
          </Button>
          <Button icon={<DownloadOutlined />} onClick={this.export} disabled={cmTotal === 0}>
            导出
          </Button>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={dataSource}
          columns={this.columns}
          rowKey={record => record.invId}
          loading={loading}
          pagination={pagination}
        />
        <Modal {...modalConfig}>
          <Form layout="horizontal">
            <FormItem {...formItemLayoutModal} label="增值税单位名称">
              {getFieldDecorator('vatCoprName', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="发票类型">
              {getFieldDecorator('invType', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <HOCSelect
                  placeholder="请选择"
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  onChange={value => this.selectinvType(value)}
                >
                  {invTypeOL}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="纳税人识别号">
              {getFieldDecorator('taxerIdNo', {
                rules: [
                  {
                    required: true,
                    message: '最大长度不超过18位的数字或字母',
                    pattern: /^[a-zA-Z0-9]{1,18}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength={19} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开户行">
              {getFieldDecorator('bankOfDepoName', {
                rules: [{ required: isRequired, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="银行账号">
              {getFieldDecorator('bankAcco', {
                rules: [
                  { required: true, message: '最大长度不超过25的数字', pattern: /^\d{1,25}$/ },
                ],
              })(<Input placeholder="请输入" maxLength={25} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开票电话">
              {getFieldDecorator('invPhone', {
                rules: [
                  {
                    required: isRequired,
                    message: '固话或手机',
                    pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength={12} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="开票地址">
              {getFieldDecorator('invAddr', {
                rules: [{ required: isRequired, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请选择' }],
              })(<Input placeholder="请输入" maxLength={200} />)}
            </FormItem>
            <Row gutter={64}>
              {!isAdd && oldFileList && oldFileList.length ? (
                <Row style={{ fontWeight: 'bold', marginBottom: 10, width: '100%' }}>
                  <Col md={{ span: 6 }} style={{ textAlign: 'right' }}>
                    发票信息附件:
                  </Col>
                  <Col md={{ span: 16 }}>
                    {oldFileList.map(item => (
                      <Col key={item.custAffixId} style={{ marginBottom: 10, marginLeft: 20 }}>
                        <a
                          onClick={e => {
                            e.preventDefault();
                            downloadFile({ fileId: item.custAffixId, fileName: item.affixName });
                          }}
                        >
                          {item.affixName}
                        </a>
                        <CloseOutlined
                          style={{
                            marginLeft: 30,
                            lineHeight: '20px',
                            color: '#40a9ff',
                            fontSize: '12px',
                          }}
                          onClick={() => this.delFile(item.custAffixId, oldFileList)} 
                        />
                      </Col>
                    ))}
                  </Col>
                </Row>
              ) : null}
              <Form.Item
                {...formItemLayoutModal}
                label={isAdd || !oldFileList.length ? '发票信息附件：' : <span>&nbsp;</span>}
                colon={false}
              >
                {getFieldDecorator('invoiceAffixList', {
                  rules: [{ required: false, message: '请输入' }],
                })(
                  <Upload {...uploadProps}>
                    <Button>
                      <UploadOutlined /> 上传附件
                    </Button>
                  </Upload>
                )}
              </Form.Item>
            </Row>
          </Form>
        </Modal>
      </div>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
